<template>
  <div class="products-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" :inline="true">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option label="未上架" value="0" />
            <el-option label="已上架" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" :icon="Plus" @click="handleCreate"
        >新增商品</el-button
      >
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
        >批量删除</el-button
      >
      <el-button
        type="success"
        :icon="Upload"
        :disabled="selectedRows.length === 0"
        @click="handleBatchPublish"
        >批量上架</el-button
      >
      <el-button
        type="info"
        :icon="Download"
        :disabled="selectedRows.length === 0"
        @click="handleBatchUnpublish"
        >批量下架</el-button
      >
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table
        ref="multipleTableRef"
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="id" label="ID" width="80" sortable /> -->
        <el-table-column label="商品图片" width="100">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="productName"
          label="商品名称"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="price" label="价格" width="100" sortable>
          <template #default="scope">
            ¥{{ Number(scope.row.price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" sortable />
        <!-- <el-table-column prop="sales" label="销量" width="80" sortable /> -->
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? "未上架" : "已上架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          sortable
        />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="success"
              link
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <!-- <el-button
              size="small"
              type="primary"
              link
              @click="handleEdit(scope.row)"
              >编辑</el-button
            > -->
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'info' : 'primary'"
              link
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? "下架" : "上架" }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              link
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新增商品' : '编辑商品'"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <!-- <el-form-item label="商品图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadImage"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item> -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="form.price"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="form.stock"
                :min="0"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="标签" prop="tags">
          <div class="tags-list">
            <div
              v-for="(item, index) in form.tags"
              :key="index"
              class="spec-item"
            >
              <el-input
                v-model="item.name"
                placeholder="名称"
                style="width: 200px"
              />
              <el-button
                type="danger"
                :icon="Delete"
                circle
                @click="removeTags(index)"
              />
            </div>
            <el-button type="primary" :icon="Plus" @click="addTags"
              >添加标签</el-button
            >
          </div>
        </el-form-item>
        <!-- <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="on">上架</el-radio>
            <el-radio label="off">下架</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="商品详情" prop="detail">
          <el-input
            v-model="form.detail"
            type="textarea"
            rows="6"
            placeholder="请输入商品详情"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="
              () => {
                dialogVisible = false;
                resetForm();
              }
            "
            >取消</el-button
          >
          <el-button type="primary" @click="submitForm" :loading="submitLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 1
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Upload,
  Download,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getProductList,
  getProductDetail,
  addProduct,
  updateProduct,
  deleteProduct,
  publishProduct,
  getProductCategoryList,
  soldOutProduct,
} from "@/api/shop";
import { useRouter } from "vue-router";

let router = useRouter();

// 数据加载状态
let loading = ref(false);
let submitLoading = ref(false);

// 选中的行
let multipleTableRef = ref();
let selectedRows = ref([]);

// 分页参数
let currentPage = ref(1);
let pageSize = ref(20);
let total = ref(0);

// 表格数据
let tableData = ref([]);

// 商品分类选项
let categoryOptions = [
  { value: "中药材", label: "中药材" },
  { value: "中药饮片", label: "中药饮片" },
  { value: "中成药", label: "中成药" },
  { value: "保健品", label: "保健品" },
  { value: "养生茶", label: "养生茶" },
  { value: "养生器具", label: "养生器具" },
];

// 搜索表单
let searchForm = reactive({
  productName: "",
  status: "",
});

// 对话框相关
let dialogVisible = ref(false);
let dialogType = ref("create"); // create or edit
let formRef = ref(null);
let form = reactive({
  productId: "",
  productName: "",
  price: 0,
  status: 0,
  detail: "",
  tags: [],
  stock: 0,
});

// 表单验证规则
let rules = {
  productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
  status: [{ required: true, message: "请选择商品状态", trigger: "change" }],
};

// 获取商品列表
let fetchData = async () => {
  loading.value = true;
  try {
    // 实际应用中应该调用API
    let res = await getProductList({
      page: currentPage.value,
      limit: pageSize.value,
      productName: searchForm.productName,
      status: searchForm.status,
    });

    console.log(res.data);
    tableData.value = res.data;
    total.value = res.total;
    loading.value = false;
  } catch (error) {
    console.error("获取商品列表失败", error);
    loading.value = false;
  }
};

// 搜索
let handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
let resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  currentPage.value = 1;
  fetchData();
};

// 分页处理
let handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

let handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 表格选择行变化
let handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 新建商品
let handleCreate = () => {
  dialogType.value = "create";
  resetForm();
  dialogVisible.value = true;
};

// 编辑商品
let handleEdit = (row) => {
  dialogType.value = "edit";
  resetForm();
  console.log(row);
  // 处理tags转换
  form.tags =
    row?.tags
      ?.split(",")
      .filter((tag) => tag.trim()) // 过滤空标签
      .map((tag) => ({ name: tag.trim() })) || []; // 转换为对象数组

  console.log(form);
  form = { ...form, ...row };

  dialogVisible.value = true;
};

// 上传图片前的校验
let beforeImageUpload = (file) => {
  let isJPG = file.type === "image/jpeg";
  let isPNG = file.type === "image/png";
  let isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 JPG 或 PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
  }
  return (isJPG || isPNG) && isLt2M;
};

// 自定义上传方法
let uploadImage = (options) => {
  let { file } = options;
  // 实际应用中应该调用后端API上传图片
  // 这里模拟一个上传过程
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    form.image = reader.result;
    ElMessage.success("图片上传成功");
  };
};

// 添加规格
let addTags = () => {
  form.tags.push({
    name: "",
  });
};

// 移除规格
let removeTags = (index) => {
  form.tags.splice(index, 1);
};

// 切换商品状态
let handleToggleStatus = (row) => {
  let statusText = row.status === 0 ? "上架" : "下架";
  ElMessageBox.confirm(`确定要${statusText}该商品吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 实际应用中应该调用API
        await publishProduct({ productId: row.productId });

        // 模拟成功
        ElMessage({
          type: "success",
          message: `${statusText}成功`,
        });
        // 重新加载数据
        fetchData();
      } catch (error) {
        console.error("操作失败", error);
        ElMessage({
          type: "error",
          message: "操作失败",
        });
      }
    })
    .catch(() => {});
};

// 删除商品
let handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该商品吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 实际应用中应该调用API
        // await deleteProduct(row.id)

        // 模拟成功
        ElMessage({
          type: "success",
          message: "删除成功",
        });

        // 重新加载数据
        fetchData();
      } catch (error) {
        console.error("删除失败", error);
        ElMessage({
          type: "error",
          message: "删除失败",
        });
      }
    })
    .catch(() => {});
};

// 批量删除
let handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个商品吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        // 实际应用中应该调用API
        // let ids = selectedRows.value.map(row => row.id)
        // await batchDeleteProducts(ids)

        // 模拟成功
        ElMessage({
          type: "success",
          message: "批量删除成功",
        });

        // 重新加载数据
        fetchData();
      } catch (error) {
        console.error("批量删除失败", error);
        ElMessage({
          type: "error",
          message: "批量删除失败",
        });
      }
    })
    .catch(() => {});
};

// 批量上架
let handleBatchPublish = () => {
  if (selectedRows.value.length === 0) return;

  ElMessageBox.confirm(
    `确定要上架选中的 ${selectedRows.value.length} 个商品吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        // 实际应用中应该调用API
        // let ids = selectedRows.value.map(row => row.id)
        // await batchChangeProductStatus(ids, 'on')

        // 模拟成功
        ElMessage({
          type: "success",
          message: "批量上架成功",
        });

        // 重新加载数据
        fetchData();
      } catch (error) {
        console.error("批量上架失败", error);
        ElMessage({
          type: "error",
          message: "批量上架失败",
        });
      }
    })
    .catch(() => {});
};

// 批量下架
let handleBatchUnpublish = () => {
  if (selectedRows.value.length === 0) return;

  ElMessageBox.confirm(
    `确定要下架选中的 ${selectedRows.value.length} 个商品吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        // 实际应用中应该调用API
        // let ids = selectedRows.value.map(row => row.id)
        // await batchChangeProductStatus(ids, 'off')

        // 模拟成功
        ElMessage({
          type: "success",
          message: "批量下架成功",
        });

        // 重新加载数据
        fetchData();
      } catch (error) {
        console.error("批量下架失败", error);
        ElMessage({
          type: "error",
          message: "批量下架失败",
        });
      }
    })
    .catch(() => {});
};

// 重置表单
let resetForm = () => {
  nextTick(() => {
    form.productId = 0;
    form.productName = "";
    form.image = "";
    form.price = 0;
    form.stock = 0;
    form.status = 0;
    form.detail = "";
    form.tags = [];
    if (formRef.value) {
      formRef.value.resetFields();
    }
  });
};

// 提交表单
let submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;

    submitLoading.value = true;
    try {
      // 实际应用中应该调用API
      if (dialogType.value === "create") {
        let tags = form.tags.map((item) => item.name)?.join(",");
        form.tags = tags;
        await addProduct(form);
      } else {
        await updateProduct(form);
      }

      // 模拟成功
      ElMessage({
        type: "success",
        message: dialogType.value === "create" ? "添加成功" : "更新成功",
      });

      // 关闭对话框并刷新数据
      dialogVisible.value = false;
      resetForm();
      fetchData();
    } catch (error) {
      console.error(
        dialogType.value === "create" ? "添加失败" : "更新失败",
        error
      );
      ElMessage({
        type: "error",
        message: dialogType.value === "create" ? "添加失败" : "更新失败",
      });
    } finally {
      submitLoading.value = false;
    }
  });
};

// 查看商品详情
let handleView = (row) => {
  router.push(`/shop/products/${row.id}`);
};

// 页面加载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.products-container {
  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    gap: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      line-height: 178px;
    }
  }

  .tags-list {
    .tags-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  }
}
</style>
